package com.lvtongka.app.ui.qr

import android.annotation.SuppressLint
import android.content.Intent
import android.text.InputFilter
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import com.lvtongka.app.R
import com.lvtongka.app.base.BaseActivity
import com.lvtongka.app.base.BaseApplication
import com.lvtongka.app.common.AppUtils
import com.lvtongka.app.common.CommonUtils
import com.lvtongka.app.common.VerifyCodeCountDownTimer
import com.lvtongka.app.common.listener.CountDownCallback
import com.lvtongka.app.common.widget.CashierInputFilter
import com.lvtongka.app.databinding.ActivityPaymentMerchantBinding
import com.lvtongka.app.dialog.CouponSelectDialog
import com.lvtongka.app.fragment.common.DialogHelper
import com.lvtongka.app.fragment.common.PasswordCallback
import com.lvtongka.app.fragment.common.SetPayCallback
import com.lvtongka.app.fragment.home.bean.TravelPassAssets
import com.lvtongka.app.fragment.home.bean.TravelPassAssetsData
import com.lvtongka.app.fragment.pay.bean.OrderInfo
import com.lvtongka.app.fragment.pay.bean.ScanDynamicsQrCodeData
import com.lvtongka.app.fragment.pay.bean.ScanQrCodeData
import com.lvtongka.app.helper.SPHelper
import com.lvtongka.app.helper.SPKConstants
import com.lvtongka.app.http.common.UrlConstants
import com.lvtongka.app.ui.coupon.bean.CouponItem
import com.lvtongka.app.ui.qr.bean.PayCfg
import com.lvtongka.app.ui.qr.bean.PayCfgCoupon
import com.lvtongka.app.ui.qr.bean.PaymentAppCancelRequest
import com.lvtongka.app.ui.qr.bean.PaymentAppRequest
import com.lvtongka.app.ui.qr.bean.PaymentCouponRequest
import com.lvtongka.app.ui.qr.bean.PaymentMerchantRequest


/**
 * describe:
 * 付款
 * @author:ZhangWei(张伟)
 * date:2024/12/12
 * time:21:28
 */
class PaymentMerchantActivity :
    BaseActivity<ActivityPaymentMerchantBinding, PaymentCodeViewModel>() {
    private val mBeanList: MutableList<CouponItem> = mutableListOf()
    private var couponSelectDialog: CouponSelectDialog? = null
    private var assetsData: TravelPassAssetsData? = null
    // 静态
    private var scanData: ScanQrCodeData? = null
    private var qrCode: String? = null
    private var passAssetsData: TravelPassAssets? = null
    private var couponItem: CouponItem? = null

    // 动态
    private var scanDynamicsData: ScanDynamicsQrCodeData? = null
    private var downTimer: VerifyCodeCountDownTimer? = null
    private var isCancel = false

    // 被扫码
    private var orderInfo: OrderInfo? = null

    private var isCoupon = false

    override fun initViewModel(): PaymentCodeViewModel {
        return ViewModelProvider(this)[PaymentCodeViewModel::class.java]
    }

    override fun initEvent() {
        binding.header.imgBack.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            if (scanDynamicsData != null) {
                // 取消订单
                isCancel = true
                showLoading("取消支付...")
                viewModel.cancelPaymentApp(PaymentAppCancelRequest(
                    scanDynamicsData!!.order_id, scanDynamicsData!!.term_id
                ))
            } else if (orderInfo != null) {
                // 取消订单
                isCancel = true
                showLoading("取消支付...")
                viewModel.cancelPaymentApp(PaymentAppCancelRequest(
                    orderInfo!!.order_id, orderInfo!!.term_id
                ))
            } else {
                setResult(RESULT_OK)
                finish()
            }
        }

        binding.tvGetCode.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            showLoading("获取中...")
            viewModel.sendNotCellSmsCode()
        }
        binding.tvNext.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            val balance = binding.etBalance.text.toString().trim()
            if (TextUtils.isEmpty(balance)) {
                showToast("请输入付款金额")
                return@setOnClickListener
            }
            val je = (balance.toDouble() * 100).toInt()
            if (scanDynamicsData != null) {
                // 动态
                dynamicsPayment(balance)
                return@setOnClickListener
            }
            if (scanData != null) {
                // 静态
                staticPayment(balance, je)
            }
            if (orderInfo != null) {
                // 动态 被扫
                dynamicOrderPayment(balance)
            }

        }
        binding.rlOtherCard.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            showLoading()
            viewModel.getCouponList(qrCode!!)
        }
        viewModel.error.observe(this) {
            hideLoading()
            showToast(it)
            if (isCancel) {
                setResult(RESULT_OK)
                finish()
            }
        }

        viewModel.travelPassAssetsData.observe(this) {
            hideLoading()
            it?.let {
                assetsData = it
                passAssetsData = it.properties[it.selected]
                binding.tvNamePhone.text = passAssetsData!!.name + "(" + passAssetsData!!.tel + ")"

                if (scanData != null) {
                    binding.tvDesc.text = "限额500"
                } else {
                    if (TextUtils.equals("1", passAssetsData!!.member_type)) {
                        binding.tvDesc.text = "优先使用旅通卡账户付款"
                    } else {
                        binding.tvDesc.text = "使用亲属卡账户付款"
                    }
                }

            }
        }

        viewModel.couponPage.observe(this) {
            hideLoading()
            it?.let {
                mBeanList.clear()
                mBeanList.addAll(it.list)
            }
            showCouponSelectDialog()
        }
        viewModel.sendAt.observe(this) {
            hideLoading()
            if (!TextUtils.isEmpty(it.send_at)) {
                downTimer = VerifyCodeCountDownTimer(
                    binding.tvGetCode,
                    60000L,
                    1000L,
                    object : CountDownCallback {
                        override fun onFinish() {
                            binding.tvGetCode.isClickable = true
                            downTimer = null
                        }
                    })
                downTimer?.start()
            }
        }
        viewModel.paymentResult.observe(this) {
            hideLoading()
            startActivity(Intent(this, PaymentCompletedActivity::class.java).apply {
                putExtra("url", UrlConstants.BASE_APP + scanData?.logo_img)
                putExtra("balance", binding.etBalance.text.toString())
                putExtra("name", scanData?.shop_name)
                putExtra("payResult", "支付成功")
                putExtra("isCoupon", isCoupon)
            })
            setResult(RESULT_OK)
            finish()
        }

        viewModel.paymentResultDt.observe(this) {
            hideLoading()
            startActivity(Intent(this, PaymentCompletedActivity::class.java).apply {
                putExtra("url", UrlConstants.BASE_APP + scanData?.logo_img)
                putExtra("balance", binding.etBalance.text.toString())
                putExtra("name", it?.shop_name)
                putExtra("payResult", "支付成功")
                putExtra("isCoupon", isCoupon)
            })
            setResult(RESULT_OK)
            finish()
        }
        viewModel.cancelResult.observe(this) {
            hideLoading()
            showToast("取消支付")
            setResult(RESULT_OK)
            finish()
        }
        viewModel.setPayType.observe(this) {
            viewModel.queryAssets()
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initData() {
        binding.header.tvTitle.text = "付款给商户"
        binding.header.imgBack.visibility = View.VISIBLE
        binding.header.statusBarView.layoutParams.height = CommonUtils.getStatusBarHeight()
        var filters = arrayOf<InputFilter>(CashierInputFilter())
        binding.etBalance.filters = filters

        qrCode = intent.getStringExtra("qrCode")
        if (intent.hasExtra("scanData")) {
            scanData = intent.getSerializableExtra("scanData") as ScanQrCodeData
        }
        if (intent.hasExtra("scanDynamicsData")) {
            scanDynamicsData =
                intent.getSerializableExtra("scanDynamicsData") as ScanDynamicsQrCodeData
        }
        if (intent.hasExtra("order_info")) {
            orderInfo = intent.getSerializableExtra("order_info") as OrderInfo
        }
        if (intent.hasExtra("isCoupon")) {
            isCoupon = intent.getBooleanExtra("isCoupon", false)
        }
        if (scanData != null) {
            Glide.with(binding.ivMerchantIcon)
                .load(UrlConstants.BASE_APP + scanData!!.logo_img)
                .error(R.mipmap.icon_home_seat)
                .into(binding.ivMerchantIcon)
        }
        if (scanDynamicsData != null) {
            Glide.with(binding.ivMerchantIcon)
                .load(UrlConstants.BASE_APP + scanDynamicsData!!.logo_img)
                .error(R.mipmap.icon_home_seat)
                .into(binding.ivMerchantIcon)
            binding.etBalance.setText(AppUtils.convertFenToYuan(scanDynamicsData!!.amt))
            if (TextUtils.equals(scanDynamicsData!!.verify_sms_flag, "1")) {
                binding.llSms.visibility = View.VISIBLE
                binding.tvCurrentPhone.text = "当前登录手机号:" + SPHelper.getString(SPKConstants.MY_CELL)
            }
        }
        if (orderInfo != null) {
            Glide.with(binding.ivMerchantIcon)
                .load(UrlConstants.BASE_APP + orderInfo!!.logo_img)
                .error(R.mipmap.icon_home_seat)
                .into(binding.ivMerchantIcon)
            binding.etBalance.setText(AppUtils.convertFenToYuan(orderInfo!!.amt))
            if (TextUtils.equals(orderInfo!!.verify_sms_flag, "1")) {
                binding.llSms.visibility = View.VISIBLE
                binding.tvCurrentPhone.text = "当前登录手机号:" + SPHelper.getString(SPKConstants.MY_CELL)
            }
        }

        if (!TextUtils.isEmpty(binding.etBalance.text.toString())) {
            binding.etBalance.isEnabled =false
        }

        showLoading()
        viewModel.queryAssets()
    }

    override fun initBinding(): ActivityPaymentMerchantBinding {
        return ActivityPaymentMerchantBinding.inflate(layoutInflater)
    }

    private fun showCouponSelectDialog() {
        couponSelectDialog = CouponSelectDialog(this, R.style.ActionSheetDialogStyle)
        couponSelectDialog?.setCouponList(mBeanList)
        couponSelectDialog?.setQsList(assetsData!!)
        couponSelectDialog?.setOnItemClickListener(object :
            CouponSelectDialog.OnConfirmClickListener {
            override fun onClickConfirm(itemBean: CouponItem?) {
                couponSelectDialog?.hideDialog()
                if (itemBean != null) {
                    // 跳转到二维码界面
                    couponItem = itemBean
                    passAssetsData = null
                    binding.tvDesc.text = "¥" + AppUtils.convertFenToYuan(itemBean.balanceCent)
                    binding.tvNamePhone.text = itemBean.typeValue
                    isCoupon = true
                }
            }

            @SuppressLint("SetTextI18n")
            override fun onClickQs(assetsData: TravelPassAssets) {
                couponSelectDialog?.hideDialog()
                passAssetsData = assetsData
                couponItem = null
                if (scanDynamicsData != null || orderInfo != null) {
                    showLoading("设置中...")
                    viewModel.setPayType(assetsData.kinship_id)
                } else {
                    binding.tvDesc.text = "限额500"
                    binding.tvNamePhone.text = passAssetsData!!.name + "(" + passAssetsData!!.tel + ")"
                }
                isCoupon = false
            }
        })
        couponSelectDialog?.show()
    }


    private fun dynamicOrderPayment(balance: String) {
        if (TextUtils.equals(orderInfo!!.verify_sms_flag, "1")) {
            if (TextUtils.isEmpty(binding.etSmsCode.text.toString())) {
                showToast("请输入短信验证码")
                return
            }
            if (TextUtils.equals(orderInfo!!.verify_password_flag, "1")) {
                DialogHelper.showPayPwdDialog(this, orderInfo!!.shop_name, "¥$balance", object :
                    PasswordCallback {

                    override fun onPasswordResult(pwd: String) {
                        // 开始付款
                        showLoading("付款中...")
                        viewModel.paymentApp(PaymentAppRequest(
                            orderInfo!!.order_id, orderInfo!!.term_id, pwd, binding.etSmsCode.text.toString()
                        ))
                    }

                    override fun onSecretFree() {

                    }
                })
            } else {
                showLoading("付款中...")
                viewModel.paymentApp(PaymentAppRequest(
                    orderInfo!!.order_id, orderInfo!!.term_id, "", binding.etSmsCode.text.toString()
                ))
            }
        } else {
            if (TextUtils.equals(orderInfo!!.verify_password_flag, "1")) {
                DialogHelper.showPayPwdDialog(this, object :
                    SetPayCallback {
                    override fun onSetPayResult(pwd: String) {
                        // 开始付款
                        showLoading("付款中...")
                        viewModel.paymentApp(PaymentAppRequest(
                            orderInfo!!.order_id, orderInfo!!.term_id, pwd, ""
                        ))
                    }
                })
            } else {
                showLoading("付款中...")
                viewModel.paymentApp(PaymentAppRequest(
                    orderInfo!!.order_id, orderInfo!!.term_id, "", "")
                )
            }
        }
    }

    private fun dynamicsPayment(balance : String) {
        if (TextUtils.equals(scanDynamicsData!!.verify_sms_flag, "1")) {
            if (TextUtils.isEmpty(binding.etSmsCode.text.toString())) {
                showToast("请输入短信验证码")
                return
            }
            if (TextUtils.equals(scanDynamicsData!!.verify_password_flag, "1")) {
                DialogHelper.showPayPwdDialog(this, scanDynamicsData!!.shop_name, "¥$balance", object :
                    PasswordCallback {

                    override fun onPasswordResult(pwd: String) {
                        // 开始付款
                        showLoading("付款中...")
                        viewModel.paymentApp(PaymentAppRequest(
                            scanDynamicsData!!.order_id, scanDynamicsData!!.term_id, pwd, binding.etSmsCode.text.toString()
                        ))
                    }

                    override fun onSecretFree() {

                    }
                })
            } else {
                showLoading("付款中...")
                viewModel.paymentApp(PaymentAppRequest(
                    scanDynamicsData!!.order_id, scanDynamicsData!!.term_id, "", binding.etSmsCode.text.toString()
                ))
            }
        } else {
            if (TextUtils.equals(scanDynamicsData!!.verify_password_flag, "1")) {
                DialogHelper.showPayPwdDialog(this, scanDynamicsData!!.shop_name, "¥$balance", object :
                    PasswordCallback {

                    override fun onPasswordResult(pwd: String) {
                        // 开始付款
                        showLoading("付款中...")
                        viewModel.paymentApp(PaymentAppRequest(
                            scanDynamicsData!!.order_id, scanDynamicsData!!.term_id, pwd, ""
                        ))
                    }

                    override fun onSecretFree() {

                    }
                })
            } else {
                showLoading("付款中...")
                viewModel.paymentApp(PaymentAppRequest(
                    scanDynamicsData!!.order_id, scanDynamicsData!!.term_id, "", "")
                )
            }
        }
    }

    private fun staticPayment(balance : String, je: Int) {
        if (couponItem != null) {
            showLoading("付款中...")
            viewModel.paymentMerchantCoupon(
                PaymentCouponRequest(
                    qrCode!!, je, PayCfgCoupon(
                        couponItem!!.memberId,
                        couponItem!!.couponNo,
                        couponItem!!.balance,
                        couponItem!!.typeId
                    )
                )
            )
            return
        }
        if (je > 50000) {
            showToast("付款金额不能大于500")
            return
        }

        val limitBalance = SPHelper.getInt(SPKConstants.MY_LIMIT_NO_PASSWORD)
        if (SPHelper.getBoolean(SPKConstants.IS_NO_PASSWORD) && je < limitBalance) {
            showLoading("付款中...")
            if (passAssetsData != null) {
                viewModel.paymentMerchant(
                    PaymentMerchantRequest(
                        qrCode!!,
                        je,
                        BaseApplication.longitude,
                        BaseApplication.latitude,
                        "",
                        PayCfg(
                            passAssetsData!!.member_type,
                            passAssetsData!!.member_id,
                            passAssetsData!!.kinship_id
                        )
                    )
                )
            }
            return
        }
        DialogHelper.showPayPwdDialog(this, scanData!!.shop_name, "¥$balance", object :
            PasswordCallback {

            override fun onPasswordResult(pwd: String) {
                // 调用接口
                showLoading("付款中...")
                if (passAssetsData != null) {
                    viewModel.paymentMerchant(
                        PaymentMerchantRequest(
                            qrCode!!,
                            je,
                            BaseApplication.longitude.toString(),
                            BaseApplication.latitude.toString(),
                            pwd,
                            PayCfg(
                                passAssetsData!!.member_type,
                                passAssetsData!!.member_id,
                                passAssetsData!!.kinship_id
                            )
                        )
                    )
                }
            }

            override fun onSecretFree() {

            }
        })
    }

    override fun onBackPressed() {
        if (scanDynamicsData != null) {
            // 取消订单
            isCancel = true
            showLoading("取消支付...")
            viewModel.cancelPaymentApp(PaymentAppCancelRequest(
                scanDynamicsData!!.order_id, scanDynamicsData!!.term_id
            ))
        } else if (orderInfo != null) {
            // 取消订单
            isCancel = true
            showLoading("取消支付...")
            viewModel.cancelPaymentApp(PaymentAppCancelRequest(
                orderInfo!!.order_id, orderInfo!!.term_id
            ))
        } else {
            setResult(RESULT_OK)
            finish()
        }
    }
}